//
//  LPCTools.m
//  WALKUP
//
//  Created by 李沛池 on 2017/3/8.
//  Copyright © 2017年 WalkUp. All rights reserved.
//

#import "LPCTools.h"
#import "LPCDefine.h"
#import <objc/runtime.h>
#import <MediaPlayer/MediaPlayer.h>
#import <CommonCrypto/CommonDigest.h>
#import <MBProgressHUD+JDragon.h>

@implementation LPCTools

//创建全局单例
+ (AppDelegate *)shareAppDelagate {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

//状态栏改变
+ (void)changeStatusBar:(BOOL)isHidden {
    [[UIApplication sharedApplication] setStatusBarHidden:isHidden];
}

//打开mail
+ (void)openEmail:(NSString *)s {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto://%@",s]]];
}
//拨打电话
+ (void)openPhone:(NSString *)s {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",s]]];
}
//打开短信
+ (void)openSms:(NSString *)s {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"sms://%@",s]]];
}
//打开浏览器
+ (void)openBrower:(NSString *)s {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@",s]]];
}

//显示下载标示
- (void)openStatusNetWorkLoad:(BOOL)isLoad {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = isLoad;
}

//去掉空格
+ (NSString *)removeWhiteSpace:(NSString *)s {
    return [s stringByReplacingOccurrencesOfString:@" " withString:@""];
}

//保存图片到相册
+ (void)saveImageToPhotos:(UIImage *)i {
    UIImageWriteToSavedPhotosAlbum(i, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}

//保存图片到相册 --> 指定回调方法
+ (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *message = @"呵呵";
    if (!error) {
        message = @"成功保存到相册";
    }else
    {
        message = [error description];
    }
    [MBProgressHUD showTipMessageInWindow:message];
}

//缩放图片
+(UIImage *)scaleImage:(UIImage *)image toWidth:(int)toWidth toHeight:(int)toHeight{
    int width=0;
    int height=0;
    int x=0;
    int y=0;
    
    if (image.size.width<toWidth){
        width = toWidth;
        height = image.size.height*(toWidth/image.size.width);
        y = (height - toHeight)/2;
    }else if (image.size.height<toHeight){
        height = toHeight;
        width = image.size.width*(toHeight/image.size.height);
        x = (width - toWidth)/2;
    }else if (image.size.width>toWidth){
        width = toWidth;
        height = image.size.height*(toWidth/image.size.width);
        y = (height - toHeight)/2;
    }else if (image.size.height>toHeight){
        height = toHeight;
        width = image.size.width*(toHeight/image.size.height);
        x = (width - toWidth)/2;
    }else{
        height = toHeight;
        width = toWidth;
    }
    
    CGSize size = CGSizeMake(width, height);
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGSize subImageSize = CGSizeMake(toWidth, toHeight);
    CGRect subImageRect = CGRectMake(x, y, toWidth, toHeight);
    CGImageRef imageRef = image.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, subImageRect);
    UIGraphicsBeginImageContext(subImageSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, subImageRect, subImageRef);
    UIImage* subImage = [UIImage imageWithCGImage:subImageRef];
    CGImageRelease(subImageRef);
    UIGraphicsEndImageContext();
    return subImage;
}

//压缩图片
+ (UIImage *)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize {
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage =UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

///用户头像的压缩上传
+ (UIImage *)compressUserAvatar_defaultImageView:(UIImage *)defaultImageView andScaledToSize:(CGSize)newSize;
{
    UIImage *newimage;
    
    
    NSData *pickImageData = UIImageJPEGRepresentation(defaultImageView, 1.0);
    NSInteger imageDataLength = (NSInteger)pickImageData.length;
    
    if (nil == defaultImageView) {
        newimage = nil;
    }
    else if (imageDataLength < 100*1024) {
        //        UIImageWriteToSavedPhotosAlbum(defaultImageView, self, nil, NULL);
        
        return defaultImageView;
        
    }
    else{
        CGSize oldsize = defaultImageView.size;
        CGRect rect;
        if (newSize.width/newSize.height > oldsize.width/oldsize.height) {
            rect.size.width = newSize.height*oldsize.width/oldsize.height;
            rect.size.height = newSize.height;
            rect.origin.x = (newSize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = newSize.width;
            rect.size.height = newSize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (newSize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(newSize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, newSize.width, newSize.height));//clear background
        [defaultImageView drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    //    UIImageWriteToSavedPhotosAlbum(newimage, self, nil, NULL);
    
    return newimage;
}

//缩小图片
+ (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

//iPhone截屏
+ (UIImage *)clipScreen:(UIView *)v size:(CGSize)size {
    //将整个v大小的图层形式创建一张图片image
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //然后将该图片保存到图片图
    //    UIImageWriteToSavedPhotosAlbum(image,self,nil,nil);
    return image;
}

//裁切
+ (UIImage *)cropImageWithImg:(UIImage *)image
                            x:(CGFloat)x
                            y:(CGFloat)y
                        width:(CGFloat)width
                       height:(CGFloat)height {
    
    CGRect rect = CGRectMake(x, y, width, height);
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    UIImage *mImage = [UIImage imageWithCGImage:imageRef];
    return mImage;
}

//获取对象下的所有属性和属性内容
+ (NSDictionary *)getModelAllAttr:(id)obj {
    NSMutableDictionary *d = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([obj class], &outCount);
    for (i = 0; i<outCount; i++) {
        objc_property_t property = properties[i];
        const char* char_f = property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        id propertyValue = [obj valueForKey:(NSString *)propertyName];
        if (propertyValue) [d setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return d;
}

//获取对象下的所有属性
+ (NSArray *)getModelAllAttrName:(id)obj {
    u_int count;
    objc_property_t *properties  =class_copyPropertyList([obj class], &count);
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i < count ; i++) {
        const char* propertyName = property_getName(properties[i]);
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    
    free(properties);
    return propertiesArray;
}

//打印IOS SDK下的字体
+ (void)enumerateFont {
    for (NSString *familyName in [UIFont familyNames]){
        NSLog(@"font family = %@",familyName);
        for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
            NSLog(@"\t  %@",fontName);
        }
    }
}

//屏幕比例系数
+ (CGFloat)getScale:(CGFloat)value {
    return value * SCREEN_SCALE;
}

//颜色值生成图片
+ (UIImage*)imageWithColor:(UIColor*)color andSize:(CGSize)size
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

//验证手机
+ (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     //    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
     */
    NSString * MOBILE = @"^1[0-9]{10}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//两张图 拼图
+ (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 img1size:(CGRect)size
{
    UIGraphicsBeginImageContext(CGSizeMake(image2.size.width*2, image2.size.height*2));
    
    //Draw image2
    [image2 drawInRect:CGRectMake(0, 0, image2.size.width*2, image2.size.height*2)];
    
    //Draw image1
    [image1 drawInRect:CGRectMake(size.origin.x*2, size.origin.y*2, size.size.width*2, size.size.height*2)];
    
    UIImage *resultImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    //    UIImageWriteToSavedPhotosAlbum(resultImage,self,nil,nil);
    return resultImage;
}

//推送日期 标题 是否每天推送
+ (void)createLocalPushWithTimeAfter:(NSInteger)date title:(NSString *)title isDayPush:(BOOL)isDayPush key:(NSString *)key {
    // 创建一个本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init] ;
    
    //删除之前的 重新添加 算更新操作
    [self RemoveLocalPushWithKey:key];
    
    //设置推送时间
    NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:date];
    
    if (notification != nil) {
        // 设置推送时间
        notification.fireDate = pushDate;
        // 设置时区
        notification.timeZone = [NSTimeZone defaultTimeZone];
        // 设置重复间隔
        if (isDayPush) {
            notification.repeatInterval = kCFCalendarUnitEra;
        }
        // 推送声音
        notification.soundName =@"sound_push.mp3";
        
        // 推送内容
        notification.alertBody = title;
        //显示在icon上的红色圈中的数子
        notification.applicationIconBadgeNumber = 1;
        //设置userinfo 方便在之后需要撤销的时候使用
        NSDictionary *info = [NSDictionary dictionaryWithObject:@"1"forKey:key];
        notification.userInfo = info;
        //添加推送到UIApplication
        UIApplication *app = [UIApplication sharedApplication];
        [app scheduleLocalNotification:notification];
    }
}

//推送日期 标题 是否每天推送
+ (void)createLocalPushWithTime:(NSString*) dateStr title:(NSString *)title isDayPush:(BOOL)isDayPush key:(NSString *)key {
    // 创建一个本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init] ;
    
    //删除之前的 重新添加 算更新操作
    [self RemoveLocalPushWithKey:key];
    
    //设置推送时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (isDayPush) {
        [formatter setDateFormat:@"HH:mm:ss"];
    }else{
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    NSDate *now = [formatter dateFromString:dateStr];
    NSDate *pushDate = now;
    if (notification != nil) {
        // 设置推送时间
        notification.fireDate = pushDate;
        // 设置时区
        notification.timeZone = [NSTimeZone defaultTimeZone];
        // 设置重复间隔
        if (isDayPush) {
            notification.repeatInterval = kCFCalendarUnitDay;
        }
        // 推送声音
        //        notification.soundName = UILocalNotificationDefaultSoundName;
        if ([dateStr isEqualToString:@"21:00:00"]) {
            notification.soundName =@"sound_push_night2.mp3";
        }else{
            notification.soundName =@"sound_push.mp3";
        }
        
        // 推送内容
        notification.alertBody = title;
        //显示在icon上的红色圈中的数子
        notification.applicationIconBadgeNumber = 1;
        //设置userinfo 方便在之后需要撤销的时候使用
        NSDictionary *info = [NSDictionary dictionaryWithObject:@"1"forKey:key];
        notification.userInfo = info;
        //添加推送到UIApplication
        UIApplication *app = [UIApplication sharedApplication];
        [app scheduleLocalNotification:notification];
    }
}

//根据key获取推送
+ (UILocalNotification*)GetLocalPushWithKey:(NSString *)key
{
    NSArray *localArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
    //声明本地通知对象
    UILocalNotification *localNotification;
    if (localArray) {
        for (UILocalNotification *noti in localArray) {
            NSDictionary *dict = noti.userInfo;
            if (dict) {
                NSString *inKey = [dict objectForKey:key];
                if (inKey) {
                    localNotification=noti;
                    if (localNotification) {
                        //不推送 取消推送
                        //[[UIApplication sharedApplication] cancelLocalNotification:localNotification];
                        return localNotification;
                    }
                }
            }
        }
    }
    return nil;
}

//根据key移除推送
+ (void)RemoveLocalPushWithKey:(NSString*)key
{
    NSArray *localArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
    //声明本地通知对象
    UILocalNotification *localNotification;
    if (localArray) {
        for (UILocalNotification *noti in localArray) {
            NSDictionary *dict = noti.userInfo;
            if (dict) {
                NSString *inKey = [dict objectForKey:key];
                if (inKey) {
                    localNotification=noti;
                    if (localNotification) {
                        //不推送 取消推送
                        [[UIApplication sharedApplication] cancelLocalNotification:localNotification];
                        
                    }
                    continue;
                }
            }
        }
    }
}

#pragma mark - 李沛池_Ver1.6.0

//POST请求字典转为字符串格式
+ (NSString *)strRequestWithDictionary:(NSDictionary *)dict
{
    if (dict == nil || dict.allKeys.count == 0) {
        return @"";
    }
    NSMutableString *strReturn = [[NSMutableString alloc] init];
    
    for (NSString *strKey in [dict allKeys]) {
        [strReturn appendString:@"&"];
        [strReturn appendString:strKey];
        [strReturn appendString:@"="];
        [strReturn appendFormat:@"%@",dict[strKey]];
    }
    
    if (strReturn.length > 0) {
        [strReturn replaceCharactersInRange:NSMakeRange(0, 1) withString:@"?"];
    }
    
    return strReturn;
}

//设置圆角(避免离屏渲染)
+ (void)avoidOffscreen:(UIImageView *)iView image:(UIImage *)image cornerRadius:(CGFloat)cornerRadius
{
    //注意第三个选项的设置
    UIGraphicsBeginImageContextWithOptions(iView.bounds.size, NO, [UIScreen mainScreen].scale);
    //在绘制之前先裁剪出一个圆形
    [[UIBezierPath bezierPathWithRoundedRect:iView.bounds
                                cornerRadius:cornerRadius] addClip];
    //图片在设置的圆形里面进行绘制
    [image drawInRect:iView.bounds];
    //获取图片
    iView.image = UIGraphicsGetImageFromCurrentImageContext();
    //结束绘制
    UIGraphicsEndImageContext();
}

//返回当前时间戳
+ (NSString *)nowTimeStampFromCurrentDate
{
    NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
    long long totalMilliseconds=1000*(long long)timestamp;
    NSString *timestampStr = [NSString stringWithFormat:@"%llu",totalMilliseconds];
    
    return timestampStr;
}

///根据时间戳返回字符串,时间的格式
+ (NSString *)TimeStampIntoTimeStringFormat:(NSString *)formatString andTimeStampString:(NSString *)timeStampString;
{
    NSTimeInterval _interval=[timeStampString doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:formatString];
    
    return [objDateformat stringFromDate:date];
}

//浮点形判断
+ (BOOL)isPureFloat:(NSString *)string
{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

//判断字符串是否有效
+ (BOOL)stringIsValid:(NSString *)string
{
    if( string == nil ||
       [string isEqualToString:@""] ||
       [string isEqualToString:@"(null)"] ||
       [string isKindOfClass:[NSNull class]]) {
        return NO;
    }
    return YES;
}

///引导用户评价walkup
+ (void)guideUserIntoAppStoreEvaluateWalkup
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:Address_APPStore]];
}

//切换页面动画 - 消失
+ (void)dismissWithAnimation:(UIView *)view viewController:(UIViewController *)sourceViewController pushToViewController:(UIViewController *)destinationViewController completion:(void(^)(void))completion
{
    UIView *blackView = [[UIView alloc] initWithFrame:FRAME_SCREEN];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0;
    [sourceViewController.view addSubview:blackView];
    
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        blackView.alpha=1;
        view.transform = CGAffineTransformMakeScale(2.0, 2.0);
    } completion:^(BOOL finished) {
        [blackView removeFromSuperview];
        view.transform = CGAffineTransformIdentity;
        if (destinationViewController == nil) {
            [sourceViewController.navigationController popViewControllerAnimated:NO];
        }else {
            [sourceViewController.navigationController pushViewController:destinationViewController animated:NO];
        }
        if (completion) {
            completion();
        }
    }];
}

//切换页面动画 - 出现
+ (void)appearWithAnimation:(UIView *)view viewController:(UIViewController *)viewController
{
    UIView *blackView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    blackView.backgroundColor=[UIColor blackColor];
    [viewController.view addSubview:blackView];
    view.transform=CGAffineTransformMakeScale(1.8, 1.8);
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        view.transform=CGAffineTransformIdentity;
        blackView.alpha=0;
    } completion:^(BOOL finished) {
        [blackView removeFromSuperview];
    }];
}

//缩小图片
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

//替换非UTF8字符
//注意：如果是三字节utf-8，第二字节错误，则先替换第一字节内容(认为此字节误码为三字节utf8的头)，然后判断剩下的两个字节是否非法；
+ (NSData *)replaceNoUtf8:(NSData *)data
{
    char aa[] = {'A','A','A','A','A','A'};                      //utf8最多6个字符，当前方法未使用
    NSMutableData *md = [NSMutableData dataWithData:data];
    int loc = 0;
    while(loc < [md length])
    {
        char buffer;
        [md getBytes:&buffer range:NSMakeRange(loc, 1)];
        if((buffer & 0x80) == 0)
        {
            loc++;
            continue;
        }
        else if((buffer & 0xE0) == 0xC0)
        {
            loc++;
            [md getBytes:&buffer range:NSMakeRange(loc, 1)];
            if((buffer & 0xC0) == 0x80)
            {
                loc++;
                continue;
            }
            loc--;
            //非法字符，将这个字符（一个byte）替换为A
            [md replaceBytesInRange:NSMakeRange(loc, 1) withBytes:aa length:1];
            loc++;
            continue;
        }
        else if((buffer & 0xF0) == 0xE0)
        {
            loc++;
            [md getBytes:&buffer range:NSMakeRange(loc, 1)];
            if((buffer & 0xC0) == 0x80)
            {
                loc++;
                [md getBytes:&buffer range:NSMakeRange(loc, 1)];
                if((buffer & 0xC0) == 0x80)
                {
                    loc++;
                    continue;
                }
                loc--;
            }
            loc--;
            //非法字符，将这个字符（一个byte）替换为A
            [md replaceBytesInRange:NSMakeRange(loc, 1) withBytes:aa length:1];
            loc++;
            continue;
        }
        else
        {
            //非法字符，将这个字符（一个byte）替换为A
            [md replaceBytesInRange:NSMakeRange(loc, 1) withBytes:aa length:1];
            loc++;
            continue;
        }
    }
    
    return md;
}

//验证邮箱是否符合基本规则
+ (BOOL)validateEmail:(NSString *)email
{
    //    NSString * p = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString * p = @"\\w+(\\.\\w)*@\\w+(\\.\\w{1,3}){1,3}";
    NSPredicate *regextestP = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", p];
    if ([regextestP evaluateWithObject:email]) {
        return YES;
    }else {
        return NO;
    }
}


#pragma mark - 李沛池_Ver2.0.1
//获取当前语言
+ (NSString *)getCurrentLanguage
{
//    if ([LPCSettingManager sharedLPCSettingManager].currentLaungua.length > 0) {
//        return [LPCSettingManager sharedLPCSettingManager].currentLaungua;
//    }
    for (NSString *strLanguage in [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"]) {
        if ([strLanguage hasPrefix:KLanguage_Chinese] || [strLanguage hasPrefix:KLanguage_English]) {
            return strLanguage;
        }
    }
    return APP_Language;
}

#pragma mark - 李沛池_OurJourney_Ver1.0.0
static CGRect oldframe;
//放大图片 全屏显示
+(void)showImage:(UIImageView *)avatarImageView
{
    UIImage *image = avatarImageView.image;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    oldframe = [avatarImageView convertRect:avatarImageView.bounds toView:window];
    backgroundView.backgroundColor = [UIColor blackColor];
    backgroundView.alpha = 0;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:oldframe];
    imageView.image = image;
    imageView.tag = 1314;
    [backgroundView addSubview:imageView];
    [window addSubview:backgroundView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideImage:)];
    [backgroundView addGestureRecognizer: tap];
    
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
        backgroundView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}

+ (void)hideImage:(UITapGestureRecognizer*)tap
{
    UIView *backgroundView = tap.view;
    UIImageView *imageView = (UIImageView*)[tap.view viewWithTag:1314];
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = oldframe;
        backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [backgroundView removeFromSuperview];
    }];
}

//截取view保存至相册
+ (void)saveImageWithView:(UIView *)view
{
    [self saveImageToPhotos:[self clipScreen:view size:view.frame.size]];
}




@end
